package configs

import (
	"bytes"
	_ "embed"
	"gin_easy_starter/pkg/env"
	"gin_easy_starter/pkg/file"
	"github.com/fsnotify/fsnotify"
	"github.com/spf13/viper"
	"io"
	"os"
	"path/filepath"
)

var (
	//go:embed dev_configs.yaml
	devConfigs []byte

	//go:embed fat_configs.yaml
	fatConfigs []byte

	//go:embed uat_configs.yaml
	uatConfigs []byte

	//go:embed pro_configs.yaml
	proConfigs []byte
)
var config = new(Config)

func init() {
	var reader io.Reader

	switch env.GetActive().Value() {
	case "dev":
		reader = bytes.NewReader(devConfigs)
	case "fat":
		reader = bytes.NewReader(fatConfigs)
	case "uat":
		reader = bytes.NewReader(uatConfigs)
	case "pro":
		reader = bytes.NewReader(proConfigs)
	default:
		reader = bytes.NewReader(fatConfigs)
	}
	viper.SetConfigType("yaml")

	if err := viper.ReadConfig(reader); err != nil {
		panic(err)
	}
	if err := viper.Unmarshal(config); err != nil {
		panic(err)
	}
	viper.SetConfigName(env.GetActive().Value() + "_configs")
	viper.AddConfigPath("./configs")
	configFile := "./configs/" + env.GetActive().Value() + "_configs.yaml"
	_, ok := file.IsExists(configFile)
	if !ok {
		if err := os.MkdirAll(filepath.Dir(configFile), 0766); err != nil {
			panic(err)
		}

		f, err := os.Create(configFile)
		if err != nil {
			panic(err)
		}
		defer f.Close()

		if err := viper.WriteConfig(); err != nil {
			panic(err)
		}
	}

	viper.WatchConfig()
	viper.OnConfigChange(func(e fsnotify.Event) {
		if err := viper.Unmarshal(config); err != nil {
			panic(err)
		}
	})
}

func Get() Config {
	return *config
}
